extends RigidBody2D

@export var bulletScene: PackedScene
var player = null
var follow_speed = 600.0
var x_follow_speed = 50.0
var direction = Vector2()
var x_offset = 450.0 
var start=false
func _ready():
	gravity_scale = 0
	player = get_tree().get_first_node_in_group("player")
	$AnimationPlayer.play("fly")

func _physics_process(delta):
	if player and start:
		direction = Vector2(0, player.position.y - position.y).normalized()
		linear_velocity.y = direction.y * follow_speed

		if position.x < player.position.x:
			var target_x = player.position.x + -x_offset
			linear_velocity.x = (target_x - position.x) * x_follow_speed * delta
			$Sprite.flip_h = false
		else:
			var target_x = player.position.x + x_offset
			linear_velocity.x = (target_x - position.x) * x_follow_speed * delta
			$Sprite.flip_h = true  # Flipped if to the left of the player


func _on_timer_timeout():
	if bulletScene:
		var bullet = bulletScene.instantiate()
		if $Sprite.flip_h:
			bullet.global_position = $gunleft.global_position  
		else:
			bullet.global_position = $gunright.global_position
		$gun.play()
		get_parent().add_child(bullet)
func _on_world_bird_start():
	start=true
	global_position.x=player.global_position.x-1000
	global_position.y = player.global_position.y
	$flap.play()


func _on_world_bird_stop():
	start=false
	$flap.stop()
